Add a macro for `return Err(human(format!(...)))`
authorAlex Crichton <alex@alexcrichton.com>
Fri, 20 Nov 2015 18:46:43 +0000 (10:46 -0800)
committerAlex Crichton <alex@alexcrichton.com>
Fri, 20 Nov 2015 18:57:03 +0000 (10:57 -0800)
This pattern showed up quite a few locations throughout the codebase but it
ended up meaning that there were some massive levels of indentation when you
actually get to the formatting string. This commit adds a new `bail!` macro
which shortens this idiom to help get the indentation under control throughout
the codebase.

28 files changed:
src/cargo/core/package_id_spec.rs
src/cargo/core/resolver/mod.rs
src/cargo/core/shell.rs
src/cargo/core/summary.rs
src/cargo/lib.rs
src/cargo/ops/cargo_clean.rs
src/cargo/ops/cargo_compile.rs
src/cargo/ops/cargo_doc.rs
src/cargo/ops/cargo_generate_lockfile.rs
src/cargo/ops/cargo_install.rs
src/cargo/ops/cargo_new.rs
src/cargo/ops/cargo_package.rs
src/cargo/ops/cargo_pkgid.rs
src/cargo/ops/cargo_run.rs
src/cargo/ops/cargo_rustc/context.rs
src/cargo/ops/cargo_rustc/custom_build.rs
src/cargo/ops/cargo_rustc/links.rs
src/cargo/ops/registry.rs
src/cargo/sources/registry.rs
src/cargo/util/config.rs
src/cargo/util/important_paths.rs
src/cargo/util/toml.rs
tests/support/mod.rs
tests/test_cargo_compile.rs
tests/test_cargo_doc.rs
tests/test_cargo_new.rs
tests/test_cargo_registry.rs
tests/test_cargo_rustdoc.rs

index 15b191e96974ea17cd7c2672d10e121331115efd..2520ba6a0960849950243cd47364dd2b7b90f3ec 100644 (file)
@@ -36,8 +36,7 @@ impl PackageIdSpec {
         };
         for ch in name.chars() {
             if !ch.is_alphanumeric() && ch != '_' && ch != '-' {
-                return Err(human(format!("invalid character in pkgid `{}`: `{}`",
-                                         spec, ch)))
+                bail!("invalid character in pkgid `{}`: `{}`", spec, ch)
             }
         }
         Ok(PackageIdSpec {
@@ -66,8 +65,7 @@ impl PackageIdSpec {
 
     fn from_url(mut url: Url) -> CargoResult<PackageIdSpec> {
         if url.query.is_some() {
-            return Err(human(format!("cannot have a query string in a pkgid: {}",
-                             url)));
+            bail!("cannot have a query string in a pkgid: {}", url)
         }
         let frag = url.fragment.take();
         let (name, version) = {
@@ -133,8 +131,8 @@ impl PackageIdSpec {
         let mut ids = i.into_iter().filter(|p| self.matches(*p));
         let ret = match ids.next() {
             Some(id) => id,
-            None => return Err(human(format!("package id specification `{}` \
-                                              matched no packages", self))),
+            None => bail!("package id specification `{}` \
+                           matched no packages", self),
         };
         return match ids.next() {
             Some(other) => {
index 465bc1a73d4a59a2abb04926cabafce8422035b4..547d7e23f8a5c60480b06defb5ea89569d54a4ab 100644 (file)
@@ -175,8 +175,7 @@ fn activate(cx: &mut Context,
     // packages we're visiting and bail if we hit a dupe.
     let id = parent.package_id().clone();
     if !cx.visited.insert(id.clone()) {
-        return Err(human(format!("cyclic package dependency: package `{}` \
-                                  depends on itself", id)))
+        bail!("cyclic package dependency: package `{}` depends on itself", id)
     }
 
     // If we're already activated, then that was easy!
@@ -557,9 +556,8 @@ fn build_features(s: &Summary, method: &Method)
             None => {
                 let feat = feat_or_package;
                 if !visited.insert(feat.to_string()) {
-                    return Err(human(format!("Cyclic feature dependency: \
-                                              feature `{}` depends on itself",
-                                              feat)))
+                    bail!("Cyclic feature dependency: feature `{}` depends \
+                           on itself", feat)
                 }
                 used.insert(feat.to_string());
                 match s.features().get(feat) {
@@ -677,10 +675,8 @@ impl Context {
             for feature in dep.features().iter() {
                 base.push(feature.clone());
                 if feature.contains("/") {
-                    return Err(human(format!("features in dependencies \
-                                              cannot enable features in \
-                                              other dependencies: `{}`",
-                                             feature)));
+                    bail!("features in dependencies cannot enable features in \
+                           other dependencies: `{}`", feature)
                 }
             }
             ret.push((dep.clone(), base));
@@ -695,9 +691,8 @@ impl Context {
                                       .collect::<Vec<&str>>();
             if unknown.len() > 0 {
                 let features = unknown.connect(", ");
-                return Err(human(format!("Package `{}` does not have these \
-                                          features: `{}`", parent.package_id(),
-                                         features)))
+                bail!("Package `{}` does not have these features: `{}`",
+                      parent.package_id(), features)
             }
         }
 
index 6e0a1956410d571e28cb5a143be010c9b1d0eb53..5c03d34c16e519346fb2aaaf22c75b3ae5a38ce0 100644 (file)
@@ -10,7 +10,7 @@ use self::AdequateTerminal::{NoColor, Colored};
 use self::Verbosity::{Verbose, Normal, Quiet};
 use self::ColorConfig::{Auto, Always, Never};
 
-use util::errors::{human, CargoResult};
+use util::errors::CargoResult;
 
 #[derive(Clone, Copy, PartialEq)]
 pub enum Verbosity {
@@ -105,7 +105,7 @@ impl MultiShell {
 
     pub fn set_verbosity(&mut self, verbose: bool, quiet: bool) -> CargoResult<()> {
         self.verbosity = match (verbose, quiet) {
-            (true, true) => return Err(human("cannot set both --verbose and --quiet")),
+            (true, true) => bail!("cannot set both --verbose and --quiet"),
             (true, false) => Verbose,
             (false, true) => Quiet,
             (false, false) => Normal
@@ -130,9 +130,8 @@ impl MultiShell {
 
             None => Auto,
 
-            Some(arg) => return Err(human(format!("argument for --color must be auto, always, or \
-                                                   never, but found `{}`",
-                                                  arg))),
+            Some(arg) => bail!("argument for --color must be auto, always, or \
+                                never, but found `{}`", arg),
         });
         Ok(())
     }
index 81445d2a3cbf54cb01815942b8a38db2519acbe2..01697171d2ff546e49c4271bac22257ad1e70322 100644 (file)
@@ -4,7 +4,7 @@ use std::mem;
 use semver::Version;
 use core::{Dependency, PackageId, SourceId};
 
-use util::{CargoResult, human};
+use util::CargoResult;
 
 /// Subset of a `Manifest`. Contains only the most important informations about
 /// a package.
@@ -23,13 +23,12 @@ impl Summary {
                features: HashMap<String, Vec<String>>) -> CargoResult<Summary> {
         for dep in dependencies.iter() {
             if features.get(dep.name()).is_some() {
-                return Err(human(format!("Features and dependencies cannot have \
-                                          the same name: `{}`", dep.name())))
+                bail!("Features and dependencies cannot have the \
+                       same name: `{}`", dep.name())
             }
             if dep.is_optional() && !dep.is_transitive() {
-                return Err(human(format!("Dev-dependencies are not allowed \
-                                          to be optional: `{}`",
-                                          dep.name())))
+                bail!("Dev-dependencies are not allowed to be optional: `{}`",
+                      dep.name())
             }
         }
         for (feature, list) in features.iter() {
@@ -41,22 +40,18 @@ impl Summary {
                 match dependencies.iter().find(|d| d.name() == dep) {
                     Some(d) => {
                         if d.is_optional() || is_reexport { continue }
-                        return Err(human(format!("Feature `{}` depends on `{}` \
-                                                  which is not an optional \
-                                                  dependency.\nConsider adding \
-                                                  `optional = true` to the \
-                                                  dependency", feature, dep)))
+                        bail!("Feature `{}` depends on `{}` which is not an \
+                               optional dependency.\nConsider adding \
+                               `optional = true` to the dependency",
+                               feature, dep)
                     }
                     None if is_reexport => {
-                        return Err(human(format!("Feature `{}` requires `{}` \
-                                                  which is not an optional \
-                                                  dependency", feature, dep)))
+                        bail!("Feature `{}` requires `{}` which is not an \
+                               optional dependency", feature, dep)
                     }
                     None => {
-                        return Err(human(format!("Feature `{}` includes `{}` \
-                                                  which is neither a dependency \
-                                                  nor another feature",
-                                                  feature, dep)))
+                        bail!("Feature `{}` includes `{}` which is neither \
+                               a dependency nor another feature", feature, dep)
                     }
                 }
             }
index 3688e958e5baace447bc078e68e7c15cc9a7bd68..ef69e02c1a4c813a68f5218749a11db67929be85 100644 (file)
@@ -38,6 +38,12 @@ use term::color::{BLACK, RED};
 
 pub use util::{CargoError, CliError, CliResult, human, Config, ChainError};
 
+macro_rules! bail {
+    ($($fmt:tt)*) => (
+        return Err(::util::human(&format_args!($($fmt)*)))
+    )
+}
+
 pub mod core;
 pub mod ops;
 pub mod sources;
index cf588ae2837f59a510c885ca3b3d6dbc3a21e6b6..e89e842d89a7381fceee00648cf4a56a86509f81 100644 (file)
@@ -32,7 +32,7 @@ pub fn clean(manifest_path: &Path, opts: &CleanOptions) -> CargoResult<()> {
     let source_id = root.package_id().source_id();
     let resolve = match try!(ops::load_lockfile(&lockfile, source_id)) {
         Some(resolve) => resolve,
-        None => return Err(human("A Cargo.lock must exist before cleaning"))
+        None => bail!("a Cargo.lock must exist before cleaning")
     };
 
     // Create a compilation context to have access to information like target
index 073d5929335e8e3fd0ffd20dadc3859481c966f4..f34de78f2433943f861ed7d8c6bb56943c23d96c 100644 (file)
@@ -33,7 +33,7 @@ use core::{Profile, TargetKind, Profiles};
 use core::resolver::{Method, Resolve};
 use ops::{self, BuildOutput, ExecEngine};
 use util::config::{ConfigValue, Config};
-use util::{CargoResult, internal, human, ChainError, profile};
+use util::{CargoResult, internal, ChainError, profile};
 
 /// Contains information about how a package should be compiled.
 pub struct CompileOptions<'a> {
@@ -156,7 +156,7 @@ pub fn compile_pkg<'a>(root_package: &Package,
     }).map(|s| s.to_string()).collect::<Vec<String>>();
 
     if jobs == Some(0) {
-        return Err(human("jobs must be at least 1"))
+        bail!("jobs must be at least 1")
     }
 
     let (packages, resolve_with_overrides, sources) = {
@@ -177,8 +177,8 @@ pub fn compile_pkg<'a>(root_package: &Package,
     };
 
     if spec.len() > 0 && invalid_spec.len() > 0 {
-        return Err(human(format!("could not find package matching spec `{}`",
-                                 invalid_spec.connect(", "))));
+        bail!("could not find package matching spec `{}`",
+              invalid_spec.connect(", "))
     }
 
     let to_builds = packages.iter().filter(|p| pkgids.contains(&p.package_id()))
@@ -202,11 +202,9 @@ pub fn compile_pkg<'a>(root_package: &Package,
                 profile.rustc_args = Some(args.to_vec());
                 general_targets.push((target, profile));
             } else {
-                return Err(human("extra arguments to `rustc` can only be \
-                                  passed to one target, consider \
-                                  filtering\nthe package by passing e.g. \
-                                  `--lib` or `--bin NAME` to specify \
-                                  a single target"))
+                bail!("extra arguments to `rustc` can only be passed to one \
+                       target, consider filtering\nthe package by passing \
+                       e.g. `--lib` or `--bin NAME` to specify a single target")
             }
         }
         (None, Some(args)) => {
@@ -218,11 +216,9 @@ pub fn compile_pkg<'a>(root_package: &Package,
                 profile.rustdoc_args = Some(args.to_vec());
                 general_targets.push((target, profile));
             } else {
-                return Err(human("extra arguments to `rustdoc` can only be \
-                                  passed to one target, consider \
-                                  filtering\nthe package by passing e.g. \
-                                  `--lib` or `--bin NAME` to specify \
-                                  a single target"))
+                bail!("extra arguments to `rustdoc` can only be passed to one \
+                       target, consider filtering\nthe package by passing e.g. \
+                       `--lib` or `--bin NAME` to specify a single target")
             }
         }
         (None, None) => {
@@ -357,7 +353,7 @@ fn generate_targets<'a>(pkg: &'a Package,
                 if let Some(t) = pkg.targets().iter().find(|t| t.is_lib()) {
                     targets.push((t, profile));
                 } else {
-                    return Err(human(format!("no library targets found")))
+                    bail!("no library targets found")
                 }
             }
 
@@ -369,9 +365,7 @@ fn generate_targets<'a>(pkg: &'a Package,
                         });
                         let t = match target {
                             Some(t) => t,
-                            None => return Err(human(format!("no {} target \
-                                                              named `{}`",
-                                                             desc, name))),
+                            None => bail!("no {} target named `{}`", desc, name),
                         };
                         debug!("found {} `{}`", desc, name);
                         targets.push((t, profile));
@@ -429,11 +423,9 @@ fn scrape_build_config(config: &Config,
     let cfg_jobs = match try!(config.get_i64("build.jobs")) {
         Some((n, p)) => {
             if n <= 0 {
-                return Err(human(format!("build.jobs must be positive, \
-                                          but found {} in {:?}", n, p)));
+                bail!("build.jobs must be positive, but found {} in {:?}", n, p)
             } else if n >= u32::max_value() as i64 {
-                return Err(human(format!("build.jobs is too large: \
-                                          found {} in {:?}", n, p)));
+                bail!("build.jobs is too large: found {} in {:?}", n, p)
             } else {
                 Some(n as u32)
             }
index 296b792c06148f4c762b47a1336bfb80901ba04b..8d843f31c93c7049418d6ed795ff34faeeef6950 100644 (file)
@@ -5,7 +5,7 @@ use std::process::Command;
 
 use core::{Package, PackageIdSpec};
 use ops;
-use util::{CargoResult, human};
+use util::CargoResult;
 
 pub struct DocOptions<'a> {
     pub open_result: bool,
@@ -28,10 +28,9 @@ pub fn doc(manifest_path: &Path,
         }
         for bin in bin_names.iter() {
             if lib_names.contains(bin) {
-                return Err(human("Cannot document a package where a library \
-                                  and a binary have the same name. Consider \
-                                  renaming one or marking the target as \
-                                  `doc = false`"))
+                bail!("cannot document a package where a library and a binary \
+                       have the same name. Consider renaming one or marking \
+                       the target as `doc = false`")
             }
         }
     }
@@ -40,8 +39,7 @@ pub fn doc(manifest_path: &Path,
 
     if options.open_result {
         let name = if options.compile_opts.spec.len() > 1 {
-            return Err(human("Passing multiple packages and `open` is not \
-                              supported"))
+            bail!("Passing multiple packages and `open` is not supported")
         } else if options.compile_opts.spec.len() == 1 {
             try!(PackageIdSpec::parse(&options.compile_opts.spec[0]))
                                              .name().replace("-", "_").to_string()
index ac5578e0c9ec9bdeddd43ab1236e494796aa022b..cd876d8d50e31925f8583dd0a63d2262567a80bc 100644 (file)
@@ -6,8 +6,8 @@ use core::registry::PackageRegistry;
 use core::{Resolve, SourceId, Package};
 use core::resolver::Method;
 use ops;
-use util::config::{Config};
-use util::{CargoResult, human};
+use util::config::Config;
+use util::CargoResult;
 
 pub struct UpdateOptions<'a> {
     pub config: &'a Config,
@@ -33,12 +33,11 @@ pub fn update_lockfile(manifest_path: &Path,
 
     let previous_resolve = match try!(ops::load_pkg_lockfile(&package)) {
         Some(resolve) => resolve,
-        None => return Err(human("A Cargo.lock must exist before it is updated"))
+        None => bail!("a Cargo.lock must exist before it is updated")
     };
 
     if opts.aggressive && opts.precise.is_some() {
-        return Err(human("cannot specify both aggressive and precise \
-                          simultaneously"))
+        bail!("cannot specify both aggressive and precise simultaneously")
     }
 
     let mut registry = PackageRegistry::new(opts.config);
index 4d1f8370a91360f114fb775b5e9bf1ff10fbe789..f65490519749ca43f841008337768bd8ad257d88 100644 (file)
@@ -147,8 +147,8 @@ fn select_pkg<'a, T>(mut source: T,
                 None => {
                     match try!(one(examples, |v| multi_err("examples", v))) {
                         Some(p) => p,
-                        None => return Err(human("no packages found with \
-                                                  binaries or examples")),
+                        None => bail!("no packages found with binaries or \
+                                       examples"),
                     }
                 }
             };
@@ -201,7 +201,7 @@ fn check_overwrites(dst: &Path,
             // get checked during cargo_compile, we only care about the "build
             // everything" case here
             if pkg.targets().iter().filter(|t| t.is_bin()).next().is_none() {
-                return Err(human("specified package has no binaries"))
+                bail!("specified package has no binaries")
             }
 
             for target in pkg.targets().iter().filter(|t| t.is_bin()) {
@@ -283,9 +283,8 @@ pub fn uninstall(root: Option<&str>,
         for bin in installed.get() {
             let bin = dst.join(bin);
             if fs::metadata(&bin).is_err() {
-                return Err(human(format!("corrupt metadata, `{}` does not \
-                                          exist when it should",
-                                          bin.display())))
+                bail!("corrupt metadata, `{}` does not exist when it should",
+                      bin.display())
             }
         }
 
@@ -299,8 +298,7 @@ pub fn uninstall(root: Option<&str>,
 
         for bin in bins.iter() {
             if !installed.get().contains(bin) {
-                return Err(human(format!("binary `{}` not installed as part \
-                                          of `{}`", bin, result)))
+                bail!("binary `{}` not installed as part of `{}`", bin, result)
             }
         }
 
index ef306f11f5c1a869407f25566ac4d233af925098..4487f3166b47ede817f691adc071af3af2aed180 100644 (file)
@@ -47,8 +47,7 @@ struct CargoNewConfig {
 pub fn new(opts: NewOptions, config: &Config) -> CargoResult<()> {
     let path = config.cwd().join(opts.path);
     if fs::metadata(&path).is_ok() {
-        return Err(human(format!("Destination `{}` already exists",
-                                 path.display())))
+        bail!("destination `{}` already exists", path.display())
     }
     let name = match opts.name {
         Some(name) => name,
@@ -74,8 +73,7 @@ pub fn new(opts: NewOptions, config: &Config) -> CargoResult<()> {
     for c in name.chars() {
         if c.is_alphanumeric() { continue }
         if c == '_' || c == '-' { continue }
-        return Err(human(&format!("Invalid character `{}` in crate name: `{}`",
-                                  c, name)));
+        bail!("Invalid character `{}` in crate name: `{}`", c, name)
     }
     mk(config, &path, name, &opts).chain_error(|| {
         human(format!("Failed to create project `{}` at `{}`",
@@ -181,8 +179,8 @@ fn discover_author() -> CargoResult<(String, Option<String>)> {
         Some(name) => name,
         None => {
             let username_var = if cfg!(windows) {"USERNAME"} else {"USER"};
-            return Err(human(format!("could not determine the current \
-                                      user, please set ${}", username_var)))
+            bail!("could not determine the current user, please set ${}",
+                  username_var)
         }
     };
     let email = git_config.and_then(|g| g.get_string("user.email").ok())
index 76eab5396b43585ab393c1902144aa416f1efc7a..b5539c1e86c87807f541ba1ba60a11ffd1497d7d 100644 (file)
@@ -136,8 +136,7 @@ fn tar(pkg: &Package, src: &PathSource, config: &Config,
        dst: &Path) -> CargoResult<()> {
 
     if fs::metadata(&dst).is_ok() {
-        return Err(human(format!("destination already exists: {}",
-                                 dst.display())))
+        bail!("destination already exists: {}", dst.display())
     }
 
     try!(fs::create_dir_all(dst.parent().unwrap()));
@@ -241,15 +240,14 @@ fn check_filename(file: &Path) -> CargoResult<()> {
     let name = match name.to_str() {
         Some(name) => name,
         None => {
-            return Err(human(format!("path does not have a unicode filename \
-                                      which may not unpack on all platforms: {}",
-                                     file.display())))
+            bail!("path does not have a unicode filename which may not unpack \
+                   on all platforms: {}", file.display())
         }
     };
     let bad_chars = ['/', '\\', '<', '>', ':', '"', '|', '?', '*'];
     for c in bad_chars.iter().filter(|c| name.contains(**c)) {
-        return Err(human(format!("cannot package a filename with a special \
-                                  character `{}`: {}", c, file.display())))
+        bail!("cannot package a filename with a special character `{}`: {}",
+              c, file.display())
     }
     Ok(())
 }
index 48fad309ec00c4cbe742adc1b366c2baca56685b..1d31a3015bdbeff5c27196ffd2d1200914a2ffa7 100644 (file)
@@ -2,7 +2,7 @@ use std::path::Path;
 
 use ops;
 use core::{PackageIdSpec, Package};
-use util::{CargoResult, human, Config};
+use util::{CargoResult, Config};
 
 pub fn pkgid(manifest_path: &Path,
              spec: Option<&str>,
@@ -13,7 +13,7 @@ pub fn pkgid(manifest_path: &Path,
     let source_id = package.package_id().source_id();
     let resolve = match try!(ops::load_lockfile(&lockfile, source_id)) {
         Some(resolve) => resolve,
-        None => return Err(human("A Cargo.lock must exist for this command"))
+        None => bail!("a Cargo.lock must exist for this command"),
     };
 
     let pkgid = match spec {
index da576189a894c8e1375f01af233e3108202ac6ea..05646e7e2cfbf9dd25c6c661542db854a8443057 100644 (file)
@@ -1,7 +1,7 @@
 use std::path::Path;
 
 use ops::{self, ExecEngine, CompileFilter};
-use util::{self, CargoResult, human, process, ProcessError};
+use util::{self, CargoResult, process, ProcessError};
 use core::Package;
 
 pub fn run(manifest_path: &Path,
@@ -19,8 +19,7 @@ pub fn run(manifest_path: &Path,
     if bins.next().is_none() {
         match options.filter {
             CompileFilter::Everything => {
-                return Err(human("a bin target must be available for \
-                                  `cargo run`"))
+                bail!("a bin target must be available for `cargo run`")
             }
             CompileFilter::Only { .. } => {
                 // this will be verified in cargo_compile
@@ -30,13 +29,13 @@ pub fn run(manifest_path: &Path,
     if bins.next().is_some() {
         match options.filter {
             CompileFilter::Everything => {
-                return Err(human("`cargo run` requires that a project only have \
-                                  one executable; use the `--bin` option to \
-                                  specify which one to run"))
+                bail!("`cargo run` requires that a project only have one \
+                       executable; use the `--bin` option to specify which one \
+                       to run")
             }
             CompileFilter::Only { .. } => {
-                return Err(human("`cargo run` can run at most one executable, \
-                                  but multiple were specified"))
+                bail!("`cargo run` can run at most one executable, but \
+                       multiple were specified")
             }
         }
     }
index 086d2782a5ffeaf528fe1ed5845189b37d7ff246..d1aad6b5e50ab79d1da1bce4d024ba733aa6149b 100644 (file)
@@ -9,7 +9,6 @@ use core::{SourceMap, Package, PackageId, PackageSet, Resolve, Target, Profile};
 use core::{TargetKind, LibKind, Profiles, Metadata, Dependency};
 use core::dependency::Kind as DepKind;
 use util::{self, CargoResult, ChainError, internal, Config, profile};
-use util::human;
 
 use super::TargetConfig;
 use super::custom_build::{BuildState, BuildScripts};
@@ -196,8 +195,7 @@ impl<'a, 'cfg> Context<'a, 'cfg> {
             (&self.target_triple, &self.target_dylib)
         };
         match *pair {
-            None => return Err(human(format!("dylib outputs are not supported \
-                                              for {}", triple))),
+            None => bail!("dylib outputs are not supported for {}", triple),
             Some((ref s1, ref s2)) => Ok((s1, s2)),
         }
     }
index 8431e81c5f9eaed83db1fa62d747c5884eec70e1..1fee049e2df82f469e9bfbd9e353ed143eb6c5c9 100644 (file)
@@ -269,8 +269,7 @@ impl BuildOutput {
             let (key, value) = match (key, value) {
                 (Some(a), Some(b)) => (a, b.trim_right()),
                 // line started with `cargo:` but didn't match `key=value`
-                _ => return Err(human(format!("Wrong output in {}: `{}`",
-                                              whence, line)))
+                _ => bail!("Wrong output in {}: `{}`", whence, line),
             };
 
             match key {
@@ -308,22 +307,20 @@ impl BuildOutput {
                 None => break
             };
             if flag != "-l" && flag != "-L" {
-                return Err(human(format!("Only `-l` and `-L` flags are allowed \
-                                         in {}: `{}`",
-                                         whence, value)))
+                bail!("Only `-l` and `-L` flags are allowed in {}: `{}`",
+                      whence, value)
             }
             let value = match flags_iter.next() {
                 Some(v) => v,
-                None => return Err(human(format!("Flag in rustc-flags has no \
-                                                  value in {}: `{}`",
-                                                  whence, value)))
+                None => bail!("Flag in rustc-flags has no value in {}: `{}`",
+                              whence, value)
             };
             match flag {
                 "-l" => library_links.push(value.to_string()),
                 "-L" => library_paths.push(PathBuf::from(value)),
 
                 // was already checked above
-                _ => return Err(human("only -l and -L flags are allowed"))
+                _ => bail!("only -l and -L flags are allowed")
             };
         }
         Ok((library_paths, library_links))
index 2021ffd75090a6e68b7513068e8562902e2192df..e2a7ad4a8226916f4227c9fb7f358046260e4a02 100644 (file)
@@ -1,7 +1,7 @@
 use std::collections::HashMap;
 
 use core::{PackageId, PackageSet};
-use util::{CargoResult, human};
+use util::CargoResult;
 
 // Validate that there are no duplicated native libraries among packages and
 // that all packages with `links` also have a build script.
@@ -13,34 +13,23 @@ pub fn validate(deps: &PackageSet) -> CargoResult<()> {
             Some(lib) => lib,
             None => continue,
         };
-        match map.get(&lib) {
-            Some(previous) => {
-                let depid = dep.package_id();
-                if previous.name() == depid.name()
-                    && previous.source_id() == depid.source_id() {
-                    return Err(human(format!("native library `{}` is being \
-                                              linked to by more than one \
-                                              version of the same package, but \
-                                              it can only be linked \
-                                              once; try updating \
-                                              or pinning your dependencies to \
-                                              ensure that this package only \
-                                              shows up once\n\n  {}\n  {}",
-                                             lib, previous, dep.package_id())))
-                } else {
-                    return Err(human(format!("native library `{}` is being \
-                                              linked to by more than one \
-                                              package, and can only be linked \
-                                              to by one package\n\n  {}\n  {}",
-                                             lib, previous, dep.package_id())))
-                }
+        if let Some(prev) = map.get(&lib) {
+            let dep = dep.package_id();
+            if prev.name() == dep.name() && prev.source_id() == dep.source_id() {
+                bail!("native library `{}` is being linked to by more \
+                       than one version of the same package, but it can \
+                       only be linked once; try updating or pinning your \
+                       dependencies to ensure that this package only shows \
+                       up once\n\n  {}\n  {}", lib, prev, dep)
+            } else {
+                bail!("native library `{}` is being linked to by more than \
+                       one package, and can only be linked to by one \
+                       package\n\n  {}\n  {}", lib, prev, dep)
             }
-            None => {}
         }
         if !dep.manifest().targets().iter().any(|t| t.is_custom_build()) {
-            return Err(human(format!("package `{}` specifies that it links to \
-                                      `{}` but does not have a custom build \
-                                      script", dep.package_id(), lib)))
+            bail!("package `{}` specifies that it links to `{}` but does not \
+                   have a custom build script", dep.package_id(), lib)
         }
         map.insert(lib, dep.package_id());
     }
index f9b6bf52bf733356adacf39c94c35354fa89b87b..4865d8d89cf0c2e1de301c52837c916edcfeb39b 100644 (file)
@@ -54,17 +54,14 @@ fn verify_dependencies(pkg: &Package, registry_src: &SourceId)
     for dep in pkg.dependencies().iter() {
         if dep.source_id().is_path() {
             if dep.specified_req().is_none() {
-                return Err(human(format!("all path dependencies must have \
-                                          a version specified when \
-                                          publishing.\n\
-                                          dependency `{}` does not specify \
-                                          a version", dep.name())))
+                bail!("all path dependencies must have a version specified \
+                       when publishing.\ndependency `{}` does not specify \
+                       a version", dep.name())
             }
         } else if dep.source_id() != registry_src {
-            return Err(human(format!("all dependencies must come from the \
-                                      same source.\ndependency `{}` comes \
-                                      from {} instead", dep.name(),
-                                     dep.source_id())))
+            bail!("all dependencies must come from the same source.\n\
+                   dependency `{}` comes from {} instead",
+                  dep.name(), dep.source_id())
         }
     }
     Ok(())
@@ -99,8 +96,7 @@ fn transmit(pkg: &Package, tarball: &Path, registry: &mut Registry)
     match *license_file {
         Some(ref file) => {
             if fs::metadata(&pkg.root().join(file)).is_err() {
-                return Err(human(format!("the license file `{}` does not exist",
-                                         file)))
+                bail!("the license file `{}` does not exist", file)
             }
         }
         None => {}
@@ -145,7 +141,7 @@ pub fn registry(config: &Config,
     let api_host = {
         let mut src = RegistrySource::new(&sid, config);
         try!(src.update().chain_error(|| {
-            human(format!("Failed to update registry {}", index))
+            human(format!("failed to update registry {}", index))
         }));
         (try!(src.config())).api
     };
@@ -319,7 +315,7 @@ pub fn yank(config: &Config,
     };
     let version = match version {
         Some(v) => v,
-        None => return Err(human("a version must be specified to yank"))
+        None => bail!("a version must be specified to yank")
     };
 
     let (mut registry, _) = try!(registry(config, token, index));
index 49d9cf20796a278856b269949aea4980e584e2f4..7a7822a670b47582c23224610ac845ff49f18fef 100644 (file)
@@ -314,7 +314,7 @@ impl<'cfg> RegistrySource<'cfg> {
         // TODO: don't download into memory (curl-rust doesn't expose it)
         let resp = try!(handle.get(url.to_string()).follow_redirects(true).exec());
         if resp.get_code() != 200 && resp.get_code() != 0 {
-            return Err(internal(format!("Failed to get 200 response from {}\n{}",
+            return Err(internal(format!("failed to get 200 response from {}\n{}",
                                         url, resp)))
         }
 
@@ -325,8 +325,7 @@ impl<'cfg> RegistrySource<'cfg> {
             state.finish()
         };
         if actual.to_hex() != expected_hash {
-            return Err(human(format!("Failed to verify the checksum of `{}`",
-                                     pkg)))
+            bail!("failed to verify the checksum of `{}`", pkg)
         }
 
         try!(paths::write(&dst, resp.get_body()));
@@ -390,7 +389,7 @@ impl<'cfg> RegistrySource<'cfg> {
                               .map(|l| self.parse_registry_package(l))
                               .collect();
                 try!(ret.chain_error(|| {
-                    internal(format!("Failed to parse registry's information \
+                    internal(format!("failed to parse registry's information \
                                       for: {}", name))
                 }))
             }
@@ -544,11 +543,11 @@ impl<'cfg> Source for RegistrySource<'cfg> {
             url.path_mut().unwrap().push(package.version().to_string());
             url.path_mut().unwrap().push("download".to_string());
             let path = try!(self.download_package(package, &url).chain_error(|| {
-                internal(format!("Failed to download package `{}` from {}",
+                internal(format!("failed to download package `{}` from {}",
                                  package, url))
             }));
             let path = try!(self.unpack_package(package, path).chain_error(|| {
-                internal(format!("Failed to unpack package `{}`", package))
+                internal(format!("failed to unpack package `{}`", package))
             }));
             let mut src = PathSource::new(&path, &self.source_id, self.config);
             try!(src.update());
index 4fe7c8dddad62c0300ea7566dfd1005b0ac1eb27..474b174f1b7ebea086186a97a0d849573ae4e36e 100644 (file)
@@ -140,10 +140,9 @@ impl Config {
                     let idx = key.split('.').take(i)
                                  .fold(0, |n, s| n + s.len()) + i - 1;
                     let key_so_far = &key[..idx];
-                    return Err(human(format!("expected table for configuration \
-                                              key `{}`, but found {} in {}",
-                                             key_so_far, val.desc(),
-                                             path.display())));
+                    bail!("expected table for configuration key `{}`, \
+                           but found {} in {}",
+                          key_so_far, val.desc(), path.display())
                 }
             }
         }
@@ -343,8 +342,8 @@ impl ConfigValue {
                     Ok((key, value))
                 }).collect::<CargoResult<_>>()), path.to_path_buf()))
             }
-            v => return Err(human(format!("found TOML configuration value of \
-                                           unknown type `{}`", v.type_str())))
+            v => bail!("found TOML configuration value of unknown type `{}`",
+                       v.type_str()),
         }
     }
 
index bca7fc3c2f0c08d86d70319493fee513de25c2fc..5ee44cf2006d2a345591e46ae6b94a631cf0e12a 100644 (file)
@@ -29,8 +29,8 @@ pub fn find_project_manifest(pwd: &Path, file: &str) -> CargoResult<PathBuf> {
         }
     }
 
-    Err(human(format!("Could not find `{}` in `{}` or any parent directory",
-                      file, pwd.display())))
+    bail!("could not find `{}` in `{}` or any parent directory",
+          file, pwd.display())
 }
 
 /// Find the root Cargo.toml
@@ -40,10 +40,10 @@ pub fn find_root_manifest_for_wd(manifest_path: Option<String>, cwd: &Path)
         Some(path) => {
             let absolute_path = cwd.join(&path);
             if !absolute_path.ends_with("Cargo.toml") {
-                return Err(human("the manifest-path must be a path to a Cargo.toml file"))
+                bail!("the manifest-path must be a path to a Cargo.toml file")
             }
             if !fs::metadata(&absolute_path).is_ok() {
-                return Err(human(format!("manifest path `{}` does not exist", path)))
+                bail!("manifest path `{}` does not exist", path)
             }
             Ok(absolute_path)
         },
index 85a7befc0b8b0157fb0cbcba7d434ed3cd0c414a..4fe58ee8e0f7bd35146e9b05aa151997bcb811a1 100644 (file)
@@ -128,9 +128,9 @@ pub fn to_manifest(contents: &[u8],
         None => {}
     }
     if !manifest.targets().iter().any(|t| !t.is_custom_build()) {
-        return Err(human(format!("no targets specified in the manifest\n  either \
-                                  src/lib.rs, src/main.rs, a [lib] section, or [[bin]] \
-                                  section must be present")))
+        bail!("no targets specified in the manifest\n  \
+               either src/lib.rs, src/main.rs, a [lib] section, or [[bin]] \
+               section must be present")
     }
     return Ok((manifest, paths));
 
@@ -374,11 +374,11 @@ impl TomlManifest {
 
         let project = self.project.as_ref().or_else(|| self.package.as_ref());
         let project = try!(project.chain_error(|| {
-            human("No `package` or `project` section found.")
+            human("no `package` or `project` section found.")
         }));
 
         if project.name.trim().is_empty() {
-            return Err(human("package name cannot be an empty string."))
+            bail!("package name cannot be an empty string.")
         }
 
         let pkgid = try!(project.to_package_id(source_id));
@@ -430,8 +430,8 @@ impl TomlManifest {
 
         for bin in bins.iter() {
             if blacklist.iter().find(|&x| *x == bin.name()) != None {
-                return Err(human(&format!("the binary target name `{}` is \
-                                           forbidden", bin.name())));
+                bail!("the binary target name `{}` is forbidden",
+                      bin.name())
             }
         }
 
index e3fbc619abda8e72a82e9073b15a06691b64d118..01004ab6e821b8fd6a4c7a8662a79336486e17cd 100644 (file)
@@ -551,10 +551,6 @@ pub fn path2url(p: PathBuf) -> Url {
     Url::from_file_path(&*p).ok().unwrap()
 }
 
-pub fn cwd() -> PathBuf {
-    env::current_dir().unwrap()
-}
-
 pub static RUNNING:     &'static str = "     Running";
 pub static COMPILING:   &'static str = "   Compiling";
 pub static DOCUMENTING: &'static str = " Documenting";
index 89b50ea0eb46b74c4eb8f26b8c95afa01cb9d678..afdfed8e8a347e4b40aa5638305c799f9e7215f4 100644 (file)
@@ -48,7 +48,7 @@ test!(cargo_compile_with_invalid_manifest {
 failed to parse manifest at `[..]`
 
 Caused by:
-  No `package` or `project` section found.
+  no `package` or `project` section found.
 "))
 });
 
@@ -211,7 +211,7 @@ test!(cargo_compile_without_manifest {
     assert_that(p.cargo_process("build"),
                 execs().with_status(101)
                        .with_stderr("\
-Could not find `Cargo.toml` in `[..]` or any parent directory
+could not find `Cargo.toml` in `[..]` or any parent directory
 "));
 });
 
index fd223b00cd173db7d4918876ef89ee02c856f379..4ce4996c0e99afbcb61656814c5fd6e9092ea084 100644 (file)
@@ -206,7 +206,7 @@ test!(doc_lib_bin_same_name {
     assert_that(p.cargo_process("doc"),
                 execs().with_status(101)
                        .with_stderr("\
-Cannot document a package where a library and a binary have the same name. \
+cannot document a package where a library and a binary have the same name. \
 Consider renaming one or marking the target as `doc = false`
 "));
 });
index 0745ebfff7b2ff36c528fb7d288a962e59f048d2..7e8f8c0239873b63ddc18ef6c82c5fe7ae1477ef 100644 (file)
@@ -87,7 +87,7 @@ test!(existing {
     fs::create_dir(&dst).unwrap();
     assert_that(cargo_process("new").arg("foo"),
                 execs().with_status(101)
-                       .with_stderr(format!("Destination `{}` already exists\n",
+                       .with_stderr(format!("destination `{}` already exists\n",
                                             dst.display())));
 });
 
index a98cb99d53a26774b2775d28310333e27b480f39..064a417a4871a6b4d4a8db6bc3d355f264cccd11 100644 (file)
@@ -166,10 +166,10 @@ test!(bad_cksum {
 unable to get packages from source
 
 Caused by:
-  Failed to download package `bad-cksum v0.0.1 (registry file://[..])` from [..]
+  failed to download package `bad-cksum v0.0.1 (registry file://[..])` from [..]
 
 Caused by:
-  Failed to verify the checksum of `bad-cksum v0.0.1 (registry file://[..])`
+  failed to verify the checksum of `bad-cksum v0.0.1 (registry file://[..])`
 "));
 });
 
index 83084fc4ff274d0e15214cedcba861f689fc1874..0951d831fbb6a9b8a1c915d0ff7ebf35fcd88674 100644 (file)
@@ -169,7 +169,7 @@ test!(rustdoc_same_name_err {
                  .arg("--").arg("--no-defaults"),
                 execs()
                 .with_status(101)
-                .with_stderr("Cannot document a package where a library and a \
+                .with_stderr("cannot document a package where a library and a \
                               binary have the same name. Consider renaming one \
                               or marking the target as `doc = false`"));
 });